package com.joshua.spring.gateway.filter;

import com.joshua.spring.gateway.constant.SwaggerConstants;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

import static com.joshua.spring.constants.MicroServiceHttpHeaders.X_FORWARDED_PREFIX;
import static com.joshua.spring.constants.MicroServiceHttpHeaders.X_REAL_SWAGGER_PATH;

/**
 * description
 * package com.joshua.spring.gateway.filter
 * classname  SwaggerHeaderFilter
 *
 * @author <a href="mailto:joshualwork@163.com">joshua_liu</a>
 * @date 2020/6/6 16:28
 */
@Component
public class SwaggerHeaderFilter extends AbstractGatewayFilterFactory {

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            String swaggerPath = request.getHeaders().getFirst(X_REAL_SWAGGER_PATH);
            if (StringUtils.isEmpty(swaggerPath)) {
                return chain.filter(exchange);
            }
            String basePath = swaggerPath.substring(0, swaggerPath.lastIndexOf(SwaggerConstants.DOCS_URI_WITH_PREFIX));
            ServerHttpRequest newRequest = request.mutate().header(X_FORWARDED_PREFIX, basePath).build();
            ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
            return chain.filter(newExchange);
        };
    }
}
